package cn.itcast.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.itcast.hibernate.domain.IdCard;
import cn.itcast.hibernate.domain.Person;

public class One2One {

	public static void main(String args[]){
		add();
		//query(1);
		queryIdCard(1);
	}
	
	public static IdCard queryIdCard(int id){
		Session s=null;
		Transaction tx=null;
		try{
			s=HibernateUtil.getSession();
			tx=s.beginTransaction();
			IdCard idCard=(IdCard)s.get(IdCard.class, id);
			System.out.println(idCard.getPerson().getName());
			tx.commit();
			return idCard;
		}finally{
			if(s!=null)
				s.close();
		}
	}
	
	public static Person query(int id){
		Session s=null;
		Transaction tx=null;
		try{
			s=HibernateUtil.getSession();
			tx=s.beginTransaction();
			Person p=(Person)s.get(Person.class, id);
			System.out.println(p.getIdCard().getUserfulLife());
			tx.commit();
			return p;
		}finally{
			if(s!=null)
				s.close();
		}
	}
	
	public static Person add(){
		Session s=null;
		Transaction tx=null;
		try{
			s=HibernateUtil.getSession();
			IdCard idCard=new IdCard();
			idCard.setUserfulLife(new Date());
			
			Person p=new Person();
			p.setName("p1");
			p.setIdCard(idCard);
			
			idCard.setPerson(p);
			
			tx=s.beginTransaction();
			s.save(p);
			s.save(idCard);
			tx.commit();
			return p;
		}finally{
			if(s!=null)
				s.close();
		}
	}
}
